#ifndef _PROCESS_POOL_HPP_
#define _PEOCESS_POOL_HPP

#include <iostream>
#include <unistd.h>
#include <vector>
#include <sys/types.h>
#include <sys/wait.h>
#include "Task.hpp"

const int gdefaultnum = 5;

class Channel
{
public:
    Channel(int fd, pid_t id)
        : _wfd(fd),
          _id(id)
    {
        _name = "channel-" + std::to_string(_wfd)+"-"+ std::to_string(_id);
    }

    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n;
    }

    void Close()
    {
        close(_wfd);
    }

    void Wait()
    {
        pid_t rid = waitpid(_id, nullptr, 0);
        (void)(rid);
    }
    ~Channel()
    {
    }

    std::string Name()
    {
        return _name;
    }

    pid_t Id()
    {
        return _id;
    }

    int Fd()
    {
        return _wfd;
    }

private:
    int _wfd;
    pid_t _id;
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager()
        : _next(0)
    {
    }

    void Insert(int wfd, pid_t id)
    {
        _channels.emplace_back(wfd, id);
    }

    Channel &Selete()
    {
        auto &c = _channels[_next];
        _next++;
        _next %= _channels.size();
        return c;
    }

    void PrintChannel()
    {
        for(auto &channel:_channels)
        {
            std::cout<<channel.Name()<<std::endl;
        }
    }

    // void StopSubProcess()
    // {
    //     for (auto &channel : _channels)
    //     {
    //         channel.Close();
    //         std::cout << "关闭：" << channel.Name() << std::endl;
    //     }
    // }

    // void WaitSubProcess()
    // {
    //     for (auto &channel : _channels)
    //     {
    //         channel.Wait();
    //         std::cout << "回收：" << channel.Name() << std::endl;
    //     }
    // }

    void CloseandWait()
    {
        // for (auto &channel : _channels)
        // {
        //     channel.Close();
        //      std::cout << "关闭：" << channel.Name() << std::endl;
        //     channel.Wait();
        //     std::cout << "回收：" << channel.Name() << std::endl;
        // }

        for (int i = _channels.size()-1;i>=0;i--)
        {
            _channels[i].Close();
             std::cout << "关闭：" << _channels[i].Name() << std::endl;
            _channels[i].Wait();
            std::cout << "回收：" << _channels[i].Name() << std::endl;
        }
    }

    ~ChannelManager()
    {
    }

private:
    std::vector<Channel> _channels;
    int _next;
};

class ProcessPool
{
public:
    ProcessPool(int num)
        : _process_num(num)
    {
        _tm.Register(PrintLog);
        _tm.Register(DownLoad);
        _tm.Register(UpLoad);
    }

    void Work(int rfd)
    {
        while (true)
        {
            int code = 0;
            ssize_t n = read(rfd, &code, sizeof(code));

            if (n > 0)
            {
                if (n != sizeof(code))
                    continue;

                std::cout << "子进程[" << getpid() << "]收到一个任务码:" << code << std::endl;
                _tm.Execute(code);
            }
            else if (n == 0)
            {
                std::cout << "子进程退出" << std::endl;
                break;
            }
            else
            {
                std::cout << "子进程读取错误" << std::endl;
                break;
            }
        }
    }
    bool Start()
    {
        for (int i = 0; i < _process_num; i++)
        {
            // 1.创建管道
            int piped[2] = {0};
            int n = pipe(piped);
            if (n < 0)
                return false;

            // 2.创建子进程
            pid_t id = fork();
            if (id < 0)
                return false;
            else if (id == 0)
            {
                // child
                // 关闭不需要的文件描述符
                close(piped[1]);
                Work(piped[0]);
                close(piped[0]);
                exit(0);
            }
            else
            {
                // parent
                // 3.关闭不需要的文件描述符
                close(piped[0]);
                _cm.Insert(piped[1], id);
            }
        }

        return true;
    }

    void Debug()
    {
        _cm.PrintChannel();
    }

    void Run()
    {
        // 1.选择一个任务
        int taskcode = _tm.Code();

        // 2.选择一个信道，负载均衡的选择一个子进程，完成任务
        auto &c = _cm.Selete();
        std::cout << "选择了一个子进程：" << c.Name() << std::endl;

        // 3.发送任务
        c.Send(taskcode);
        std::cout << "发送了一个任务码：" << taskcode << std::endl;
    }

    void Stop()
    {
        _cm.CloseandWait();
        
    }
    ~ProcessPool()
    {
    }

private:
    int _process_num;
    ChannelManager _cm;
    TaskManager _tm;
};

#endif